<?php

namespace app\api\controller;

use app\api\service\UserToken;
use app\api\validate\OauthGet;
use app\api\model\Oauth AS OauthModel;

class Oauth extends Base
{
    /**
     * 获取授权的用户信息
     * @return array
     * @throws \think\Exception\DbException
     */
    public function getUserInfo()
    {
        $encryptedData = $data['encryptedData'] = input('encryptedData');
        $iv = $data['iv'] = input('iv');

        // 检测变量
        $validate = new OauthGet();
        if (!$validate->check($data)) {
            return self::sendResult(102, [], $validate->getError());
        }

        if ($this->tokenValue['session_key'] == "") {
            return self::sendResult(104, [], $validate->getError());
        }

        // 缓存中的session_key
        $sessionKey = $this->tokenValue['session_key'];

        $userToken = new UserToken();
        $res = $userToken->getUserInfo($sessionKey, $encryptedData, $iv);
        return self::sendResult($res['code'], $res['data'], $res['msg']);
    }

    /**
     * 绑定手机号码
     * https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html
     * @return array
     * @throws \think\Exception\DbException
     */
    public function getPhone()
    {
        $encryptedData = $data['encryptedData'] = input('encryptedData');
        $iv = $data['iv'] = input('iv');
        // 检测变量
        $validate = new OauthGet();
        if (!$validate->check($data)) {
            return self::sendResult(102, [], $validate->getError());
        }

        if ($this->tokenValue['openid'] == "") {
            return self::sendResult(104, [], $validate->getError());
        }

        // 缓存中的session_key
        $openid = $this->tokenValue['openid'];
        $sessionKey = $this->tokenValue['session_key'];
        $userToken = new UserToken();
        $res = $userToken->getPhone($openid, $sessionKey, $encryptedData, $iv);
        return self::sendResult($res['code'], $res['data'], $res['msg']);
    }


    /**
     * 封禁账号
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function delUser()
    {

        $oauthId = $this->oauthInfo['id'];
        OauthModel::updateStatus($oauthId, 0);

        return self::sendResult(self::$okCode, [], '注销成功');
    }
}